#include "GScrolledWindow.h"

#include "GBox.h"
#include "GLabel.h"
#include "Object.h"

#define G_SCROLLED_LINES 10

struct _GScrolledWindow
{
        GWidget  parent_instance;
        GWidget *main_box;
        GWidget *labels[G_SCROLLED_LINES];
        /* 当前文字所在行 */
        uint8_t line;
        /* 是否自动渲染窗口 */
        bool will_auto_render;
};

static uint16_t
g_scrolled_window_get_min_width(GScrolledWindow *self)
{
        return SCREEN_WIDTH;
}

static uint16_t
g_scrolled_window_get_min_height(GScrolledWindow *self)
{
        return SCREEN_HEIGHT;
}

static void
g_scrolled_window_render(const GScrolledWindow *self,
                         uint16_t               startX,
                         uint16_t               startY,
                         uint16_t               endX,
                         uint16_t               endY)
{
        if (G_WIDGET(self)->force_render)
                g_widget_set_force_render(self->main_box);

        startX += G_WIDGET(self)->margin;
        startY += G_WIDGET(self)->margin;
        endX -= G_WIDGET(self)->margin;
        endY -= G_WIDGET(self)->margin;
        g_widget_render(self->main_box, startX, startY, endX, endY);
}

void
g_scrolled_window_set_auto_render(GScrolledWindow *self, bool will_auto_render)
{
        g_widget_set_force_render(G_WIDGET(self));
        self->will_auto_render = will_auto_render;
}

GWidget *
g_scrolled_window_new(void)
{
        GScrolledWindow *self = object_new(GScrolledWindow);
        g_widget_init(G_WIDGET(self),
                      G_WIDGET_NUMS_CALLBACK(g_scrolled_window_get_min_width),
                      G_WIDGET_NUMS_CALLBACK(g_scrolled_window_get_min_height),
                      G_WIDGET_RENDER(g_scrolled_window_render));
        self->main_box = g_box_new(G_ORIENTATION_VERTICAL, true);
        for (uint8_t i = 0; i < G_SCROLLED_LINES; ++i) {
                self->labels[i] = g_label_new();
                g_box_append(G_BOX(self->main_box), self->labels[i]);
        }
        self->line             = 0;
        self->will_auto_render = false;
        return G_WIDGET(self);
}

void
g_scrolled_window_add_text(GScrolledWindow *self, const unsigned char *text)
{
        if (self->line >= G_SCROLLED_LINES)
                self->line = 0;
        g_label_set_text(G_LABEL(self->labels[self->line]), text);
        self->line += 1;

        if (self->will_auto_render)
                g_widget_render(G_WIDGET(self), 0, 0, 239, 319);
}
